#!/usr/bin/python3
#
# Copyright (C) 2012-2013 Gameloft
# alexandr.soor@gameloft.com
# nikolay.yakovlev@gameloft.com
# 13.03.2013

import os
import sys
import json
import shutil

from federation import Federation
import hashlib

def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    return md5.digest()




def start(auth, settings, save_to_svn, desc):
    clientid = open('current_data/clientid', 'r').read().replace('\n', '')
    print(clientid)
    fed = Federation(clientid, settings.federation_user_name, settings.federation_password)

    from cryptTEA2 import CryptTEA
    c = CryptTEA(False)


    iris = fed.load_iris()
    iris.upload('out.tea', settings.federation_iris_keyname)
    data = iris.get(settings.federation_iris_keyname)
    z = open('tmp.tea', 'w+b')
    z.write(data)
    z.close()


    # if md5_for_file(open('out.tea','r+b')) != md5_for_file(open('tmp.tea','r+b')):
        # raise Exception('Iris Broken')

    shutil.copyfile('out.tea', settings.svn_output_file)

    if auth.is_admin() and save_to_svn == 'true':
        print('up')
        os.system('svn up %s --accept mine-full' % settings.svn)
        print('commit')
        cmd = 'svn commit -m "* [auto] %s" %s' % ( desc.split('<br>')[0], settings.svn)
        print(cmd)
        os.system(cmd)
        print('debug')

    os.remove('out.tea')
    os.remove('tmp.tea')
